package com.cakeclient.clientsoap;

import com.cakeclient.clientsoap.Exception.SoapClientException;
import com.cakeclient.clientsoap.Exception.SoapComException;
import com.cakeclient.clientsoap.contract.ContractObject;
import org.ksoap2.serialization.SoapObject;

import java.util.Map;

public class ObjectMethod<T extends ContractObject> extends Method<T> {

    public ObjectMethod(SoapClient soapClient, String methodName, Map<String, Object> parameters) {
        super(soapClient, methodName, parameters);
    }

    public ObjectMethod(SoapClient soapClient, String methodName, Map<String, Object> parameters, Class<T> type) {
        super(soapClient, methodName, parameters);
        this.type = type;

    }

    private Class<T> type;


    @Override
    public T getResult(Class<T> type) throws SoapComException, SoapClientException {
        Object response = executeCall();
        if (response instanceof SoapObject) {
            try {
                T instance = type.newInstance();
                instance.fill((SoapObject) response);
                return instance;
            } catch (Exception e) {
                SoapClientException se = new SoapClientException(e.getMessage());
                se.setStackTrace(e.getStackTrace()) ;
                throw se;
            }
        } else {
            throw new SoapClientException();
        }
    }

    @Override
    public T getResult() throws SoapComException, SoapClientException {
        return this.getResult(type);
    }
}
